package net.javashop.admin.web.controller.sso;

import javax.servlet.http.HttpSession;

import net.javashop.biz.manager.ManagerBiz;
import net.javashop.entity.Manager;
import net.javashop.util.encryption.EncryptUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * 后台用户登录处理控制器
 * @author wqq
 *
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
	private static Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private ManagerBiz managerBiz;
	
	@RequestMapping(value="/login.html", method=RequestMethod.POST)
	public ModelAndView login(@RequestParam String username, @RequestParam String password, @RequestParam String checkCode, HttpSession session){
		//页面必须传递3个参数,如果页面没有对应的 name=username的表单域,那么将出现404 The request sent by the client was syntactically incorrect

		ModelAndView mav = new ModelAndView();
		
		//校验用户名密码不能为空
		if(StringUtils.isBlank(username) || StringUtils.isEmpty(password)){
			mav.addObject("msg", "用户名或者密码不正确!");
			mav.setViewName("common/login");
			return mav;
		}
		
		//校验验证码是否正确
		String rand = (String)session.getAttribute("checkcode_rand");
		if(StringUtils.isBlank(rand) || StringUtils.isBlank(checkCode) || !StringUtils.equalsIgnoreCase(rand, checkCode)){
			mav.addObject("msg", "验证码不正确!");
			mav.setViewName("common/login");
			return mav;
		}
		
		//校验用户名是否存在
		Manager manager = managerBiz.getManagerByUsername(username);
		if(manager==null){
			mav.addObject("msg", "用户名或者密码不正确!");
			mav.setViewName("common/login");
			//TODO 记录登录操作日志,登录失败
			return mav;
		} else {
			//验证密码是否一致
			String pwd = manager.getPassword();
			if(!EncryptUtil.checkPassword(pwd, password)){
				mav.addObject("msg", "用户名或者密码不正确!");
				mav.setViewName("common/login");
				//TODO 记录登录操作日志,登录失败
				return mav;
			}
		}
		
		
		//TODO 记录最后登录时间,最后登录IP,记录登录次数
		//TODO 检查登录次数,并锁定该用户不允许登录,使用最后登录时间来锁定.
		//TODO 将用户的角色,权限编号存入session,在application中会存放所有的权限信息
		//TODO 记录登录操作日志,登录成功
		
		//登录成功,重定向到后台首页.
		mav.setViewName("redirect:/admin/home.html");
		return mav;
		
		
	}
}
